package com.dhecp.project.logstics.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.dhecp.common.annotation.Log;
import com.dhecp.common.annotation.RepeatSubmit;
import com.dhecp.common.core.domain.AjaxResult;
import com.dhecp.common.core.page.TableDataInfo;
import com.dhecp.common.enums.BusinessType;
import com.dhecp.common.utils.DateUtils;
import com.dhecp.common.utils.TypeUtils;
import com.dhecp.core.constant.ModuleTable;
import com.dhecp.core.layui.GridColumnsPropertyModel;
import com.dhecp.core.utils.ExportExcelUtils;
import com.dhecp.framework.util.ShiroUtils;
import com.dhecp.project.common.controller.BaseModuleController;
import com.dhecp.project.logstics.domain.FbaDispatch;
import com.dhecp.project.logstics.service.FbaBoxDetailService;
import com.dhecp.project.logstics.service.FbaDispatchService;
import com.dhecp.project.system.domain.SysDictionaryForExport;
import com.dhecp.project.system.service.SysDictionaryForFieldService;

/**
 * @program: kjecp
 * @description: 头程发货单 控制层
 * @author: hlf
 * @create: 2022-10-13 15:13
 */
@Controller
@RequestMapping("/logstics/fbaDispatch")
public class FbaDispatchController extends BaseModuleController {

    private String prefix = "logstics/fbaDispatch";
    private String moduleTable = ModuleTable.FBA_DISPATCH;

    @Autowired
    private FbaDispatchService fbaDispatchService;

    @Autowired
    private GridColumnsPropertyModel gridColumnsPropertyModel;

    @Autowired
    private SysDictionaryForFieldService dictionaryForFieldService;

    @Autowired
    private FbaBoxDetailService fbaBoxDetailService;


    /**
     * @Description: 打开查询列表页
     * @Param: [params]
     * @return: org.springframework.web.servlet.ModelAndView
     * @Author: hlf
     * @date: 2022-08-15 15:42
     */
    @RequiresPermissions("logstics:fbaDispatch:view")
    @GetMapping()
    public ModelAndView view(@RequestParam Map<String, Object> params) {
        params.put("moduleTable", moduleTable);
        params.put("entity", new FbaDispatch()); //生成表格gridColumns对应的实体，用于获取实体属性生成表格字段
        params.put("prefix", prefix + "/fbaDispatch"); //页面路径
        params.put("toolBarWidth", 200);

        ModelAndView mv = this.openListPage(params);
        mv.addObject("business", "fbaDispatch");
        return mv;
    }

    /**
     * @Description: 打开制单页
     * @Param: nid 必要参数：单据编码（新增时传默认值 0 ，修改、查看时传单据实际值）
     * @return: org.springframework.web.servlet.ModelAndView
     * @Author: hlf
     * @date: 2022-08-15 15:42
     */
    @RequiresPermissions("logstics:fbaDispatch:view")
    @GetMapping("/edit")
    public ModelAndView editPage(@RequestParam Map<String, Object> params) {
        if (params.get("nid") == null || params.get("nid") == "") {
            params.put("nid", "0");
        }
        params.put("moduleTable", moduleTable);
        params.put("entity", new FbaDispatch()); //用于获取实体属性名取代对应字典字段名，解决大小写敏感问题
        params.put("moduleUrl", prefix); //页面上级路径
        params.put("prefix", prefix + "/fbadispatch_edit"); //页面路径
        Subject userSubject = ShiroUtils.getSubject();
        int enableEdit = 0;
        boolean vType = false;
        if (params.get(enableEdit) == null || "1".equals(params.get(enableEdit).toString())) {
            if (userSubject.isPermitted("logstics:fbaDispatch:edit")) { //当前登录用户主体是否有修改的权限
                enableEdit = 1;
            }
        }

        try {
            Map<String, Object> headData = new HashMap<String, Object>();        //表头的业务数据
//          SysModuleSet moduleSet = sysModuleSetService.queryModuleSet(params);//单据设置信息
            FbaDispatch entityData = fbaDispatchService.queryFirstRecord(params);
            headData = TypeUtils.entityToMap(entityData);
            params.put("headData", headData); //表头的业务数据

            params.put("checkBox", "yes"); //生成表格gridColumns时包含复选
            ModelAndView mv = this.openEditPage(params);
            mv.addObject("headData", headData);
            mv.addObject("nowTimeStr", DateUtils.getDate());    //当前日期
            mv.addObject("enableEdit", vType ? 0 : enableEdit); //当前页面是否可编辑（0：不可编辑，1：可编辑）
            if (entityData != null) {
                Map<String, Object> params2 = new HashMap<String, Object>();
                params2.put("moduleTable", moduleTable);
                params2.put("codePlanOrder",entityData.getCodePlanOrder());
                params2.put("num","2");
                mv.addObject("List", fbaBoxDetailService.queryList(params2));//母件数据
            }
            params.put("readOnly", vType);//生成列是否可编辑
            params.put("toolBarWidth", 0);//操作区
            params.put("getFieldAttributesType", "pageingrid");//pageingrid：网格字段
            mv.addObject("gridColumnsZJ", gridColumnsPropertyModel.queryGridColumnsPropertyModel(params));

            return mv;
        } catch (Exception e) {
            return this.gotoModelAndViewErrorPage(e.getMessage());    //详细信息
        }

    }

    /**
     * @Description: 查询页 列表数据
     * @Param: [params]
     * @return: com.dhecp.common.core.page.TableDataInfo
     * @Author: hlf
     * @date: 2022-08-15 15:43
     */
    @RequiresPermissions("logstics:fbaDispatch:list")
    @GetMapping("/list")
    @ResponseBody
    public TableDataInfo list(@RequestParam Map<String, Object> params) {
        params.put("moduleTable", moduleTable);
        if (params.get("num").equals("0")){
            params.put("state", "0");
        } else {
            params.put("state", "1");
        }
        List<FbaDispatch> list = new ArrayList<FbaDispatch>();
        try {
            list = fbaDispatchService.queryList(params);
        } catch (Exception e) {
            e.printStackTrace();
            return getDataTable(this.getExceptionMessage(e).toString());
        }
        return getDataTable(list);
    }

    /**
     * @Description: 数据导出Excel
     * @Param: [params]
     * @return: com.dhecp.common.core.domain.AjaxResult
     * @Author: hlf
     * @date: 2022-08-15 15:43
     */
    @RequiresPermissions("logstics:fbaDispatch:export")
    @Log(title = "头程发货数据导出", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    @ResponseBody
    @RepeatSubmit
    public AjaxResult export(@RequestParam Map<String, Object> params) throws Exception {
        params.put("moduleTable", moduleTable);
        params.put("entity", new FbaDispatch());

        List<FbaDispatch> list = fbaDispatchService.queryList(params);

        params.put("getFieldAttributesType", "export");
        List<SysDictionaryForExport> fieldList = dictionaryForFieldService.queryExportFieldList(params);
        ExportExcelUtils<FbaDispatch> util = new ExportExcelUtils<FbaDispatch>(moduleTable, new FbaDispatch());
        String sheeName = "";
        if (params.get("num").equals("2")){
            sheeName = "头程发货单";
        } else {
            sheeName = "头程完成单";
        }
        return util.exportExcel(list, fieldList, sheeName, "export");
    }
//
    /**
     * @Description: 保存数据
     * @Param: infoMap 必要参数：非网格字段（包括头部、底部所有显示和隐藏的字段）
     * @Param: infoItems 必要参数：对应实体类的json格式字符串
     * @return: com.dhecp.common.core.domain.AjaxResult
     * @Author: hlf
     * @date: 2022-08-15 15:44
     */
    @RequiresPermissions(value = {"logstics:fbaDispatch:add", "logstics:fbaDispatch:edit", "logstics:fbaDispatch:delete"}, logical = Logical.OR)
    @Log(title = "头程装箱单", businessType = BusinessType.UPDATE)
    @PostMapping("/editpost")
    @ResponseBody
    @RepeatSubmit
    public AjaxResult editpost(@RequestParam Map<String, Object> params) {
        params.put("moduleTable", moduleTable);
        AjaxResult ajaxResult = new AjaxResult();
        try {
            ajaxResult = fbaDispatchService.saveData(params);
        } catch (Exception e) {
            ajaxResult = AjaxResult.error(this.getExceptionMessage(e));
        }
        return ajaxResult;
    }

    /**
     *@Description: 流转
     *@Param: [params] infoMap 必要参数：非网格字段（包括头部、底部所有显示和隐藏的字段）
     *@Param: [params] infoItems 必要参数：对应实体类的json格式字符串（仅需 guid）
     *@return: com.dhecp.common.core.domain.AjaxResult
     *@Author: hlf
     *@date: 2022-05-09 11:42
     */
    @RequiresPermissions("logstics:fbaDispatch:flow")
    @Log(title = "发货审核", businessType = BusinessType.FLOWGO)
    @PostMapping("/updateState")
    @ResponseBody
    @RepeatSubmit
    public AjaxResult updateState(@RequestParam Map<String, Object> params){
        params.put("moduleTable", moduleTable);
        AjaxResult ajaxResult = new AjaxResult();
        try {
            ajaxResult= fbaDispatchService.updateFlowGo(params);
        }catch (Exception e) {
            ajaxResult = AjaxResult.error(this.getExceptionMessage(e));
        }
        return ajaxResult;
    }

    /**
     *@Description: 退回
     *@Param: [params] infoMap 必要参数：非网格字段（包括头部、底部所有显示和隐藏的字段）
     *@Param: [params] 必要参数：对应实体类的json格式字符串（仅需 guid）
     *@return: com.dhecp.common.core.domain.AjaxResult
     *@Author: hlf
     *@date: 2022-05-09 11:42
     */
    @RequiresPermissions("logstics:fbaDispatch:flow")
    @Log(title = "发货", businessType = BusinessType.FLOWBACK)
    @PostMapping("/flowbackpost")
    @ResponseBody
    @RepeatSubmit
    public AjaxResult flowBackSave(@RequestParam Map<String, Object> params){
        params.put("moduleTable", moduleTable);
        AjaxResult ajaxResult = new AjaxResult();
        try {
            ajaxResult= fbaDispatchService.updateFlowBack(params);
        }catch (Exception e) {
            ajaxResult = AjaxResult.error(this.getExceptionMessage(e));
        }
        return ajaxResult;
    }

    /**
     *@Description: 拆箱动作
     *@Param: [params] infoMap 必要参数：非网格字段（包括头部、底部所有显示和隐藏的字段）
     *@Param: [params] infoItems 必要参数：对应实体类的json格式字符串（仅需 guid）
     *@return: com.dhecp.common.core.domain.AjaxResult
     *@Author: hlf
     *@date: 2022-05-09 11:42
     */
    @RequiresPermissions("logstics:fbaDispatch:flow")
    @Log(title = "发货审核", businessType = BusinessType.FLOWGO)
    @PostMapping("/devanningPost")
    @ResponseBody
    @RepeatSubmit
    public AjaxResult devanningPost(@RequestParam Map<String, Object> params){
        AjaxResult ajaxResult = new AjaxResult();
        try {
            ajaxResult= fbaDispatchService.devanningPost(params);
        }catch (Exception e) {
            ajaxResult = AjaxResult.error(this.getExceptionMessage(e));
        }
        return ajaxResult;
    }
}